package com.util;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDP {
	//发送
	public static int setSocket(String ip,byte[] buf,int lenth,int port){
		InetAddress ia=null;
		int LocalPort = 0;
		try {
			DatagramSocket socket = new DatagramSocket(); 
			LocalPort = socket.getLocalPort();
			ia = InetAddress.getByName(ip);
			DatagramPacket dp = new DatagramPacket(buf, lenth, ia, port);
			socket.send(dp);
			socket.close();
			// 关闭此数据报套接字。  
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return LocalPort;
	}
	
	//接收
	public static byte[] getSocket(int port){
		String str ="";
		byte [] buf = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf, 1024);
		try {
		
			   DatagramSocket socket = new DatagramSocket(port);  
			   socket.setSoTimeout(5000);
			   socket.receive(dp);
			   
	          
			str = new String(dp.getData(), 0, dp.getLength());	
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return dp.getData();
	}
	
	
}
